<?php
namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\BlackCardRecharge;
use plugin\ky_black\app\admin\model\BlackCard;
use plugin\ky_black\app\admin\model\CardBalanceLog;
use support\Db;

class BlackCardRechargeController extends BaseController
{
    /**
     * 充值记录列表
     */
    public function list(Request $request): Response
    {
        $page = (int)$request->input('page', 1);
        $pageSize = (int)$request->input('limit', 15);
        $keyword = $request->input('keyword', '');
        $status = $request->input('status', '');
        $verifyStatus = $request->input('verify_status', '');
        $startTime = $request->input('start_time', '');
        $endTime = $request->input('end_time', '');

        $query = BlackCardRecharge::with(['blackCard', 'organization']);

        // 关键词搜索
        if ($keyword) {
            $query->where(function ($q) use ($keyword) {
                $q->where('recharge_no', 'like', "%{$keyword}%")
                  ->orWhere('black_card_no', 'like', "%{$keyword}%")
                  ->orWhere('payment_account', 'like', "%{$keyword}%");
            });
        }

        // 状态筛选
        if ($status !== '') {
            $query->where('status', $status);
        }

        // 核实状态筛选
        if ($verifyStatus !== '') {
            $query->where('verify_status', (int)$verifyStatus);
        }

        // 时间范围筛选
        if ($startTime) {
            $query->where('created_at', '>=', $startTime);
        }
        if ($endTime) {
            $query->where('created_at', '<=', $endTime);
        }

        $total = $query->count();
        $list = $query->orderBy('recharge_id', 'desc')
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->get();

        return $this->success([
            'list' => $list,
            'total' => $total
        ]);
    }

    /**
     * 创建充值记录
     */
    public function create(Request $request): Response
    {
        $data = $request->post();

        // 验证黑卡是否存在
        $blackCard = BlackCard::where('card_no', $data['black_card_no'])->first();
        if (!$blackCard) {
            return $this->error('黑卡不存在');
        }

        // 生成充值单号
        $data['recharge_no'] = BlackCardRecharge::generateRechargeNo();
        $data['black_card_id'] = $blackCard->card_id;
        $data['status'] = 'pending';

        try {
            $recharge = BlackCardRecharge::create($data);
            return $this->success($recharge, '创建成功');
        } catch (\Exception $e) {
            return $this->error('创建失败：' . $e->getMessage());
        }
    }

    /**
     * 核实充值
     */
    public function verify(Request $request): Response
    {
        $rechargeId = $request->input('recharge_id');
        if (!$rechargeId) {
            return $this->error('参数错误');
        }

        try {
            Db::transaction(function () use ($rechargeId) {
                $recharge = BlackCardRecharge::findOrFail($rechargeId);
                
                if ($recharge->verify_status) {
                    throw new \Exception('该充值记录已核实');
                }

                if ($recharge->status !== 'pending') {
                    throw new \Exception('只能核实充值中的记录');
                }

                $blackCard = BlackCard::where('card_no', $recharge->black_card_no)->lockForUpdate()->first();
                if (!$blackCard) {
                    throw new \Exception('黑卡不存在');
                }

                // 更新充值记录状态
                $recharge->verify_status = true;
                $recharge->verify_time = date('Y-m-d H:i:s');
                $recharge->effect_time = date('Y-m-d H:i:s');
                $recharge->status = 'success';
                $recharge->save();

                // 更新黑卡余额
                $beforeBalance = $blackCard->balance;
                $blackCard->balance += $recharge->amount;
                $blackCard->available_balance += $recharge->amount;
                $blackCard->save();

                // 记录余额变动
                CardBalanceLog::create([
                    'card_id' => $blackCard->card_id,
                    'card_no' => $blackCard->card_no,
                    'change_type' => 'recharge',
                    'amount' => $recharge->amount,
                    'before_balance' => $beforeBalance,
                    'after_balance' => $blackCard->balance,
                    'before_available' => $beforeBalance,
                    'after_available' => $blackCard->available_balance,
                    'before_frozen' => $blackCard->frozen_balance,
                    'after_frozen' => $blackCard->frozen_balance,
                    'operator_id' => $request->user->staff_id ?? 0,
                    'operator_name' => $request->user->real_name ?? '系统',
                    'remark' => "充值单号：{$recharge->recharge_no}"
                ]);
            });

            return $this->success(null, '核实成功');
        } catch (\Exception $e) {
            return $this->error('核实失败：' . $e->getMessage());
        }
    }

    /**
     * 取消充值
     */
    public function cancel(Request $request): Response
    {
        $rechargeId = $request->input('recharge_id');
        if (!$rechargeId) {
            return $this->error('参数错误');
        }

        try {
            $recharge = BlackCardRecharge::findOrFail($rechargeId);
            
            if ($recharge->status !== 'pending') {
                return $this->error('只能取消充值中的记录');
            }

            $recharge->status = 'failed';
            $recharge->save();

            return $this->success(null, '取消成功');
        } catch (\Exception $e) {
            return $this->error('取消失败：' . $e->getMessage());
        }
    }

    /**
     * 获取充值详情
     */
    public function detail(Request $request): Response
    {
        $rechargeId = $request->input('id');
        if (!$rechargeId) {
            return $this->error('参数错误');
        }

        $recharge = BlackCardRecharge::with(['blackCard', 'organization'])->find($rechargeId);
        if (!$recharge) {
            return $this->error('充值记录不存在');
        }

        return $this->success($recharge);
    }
} 